package com.demo.gulimall.canal.copy;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry.*;
import com.alibaba.otter.canal.protocol.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author lxf
 * @description 依据MySQL binlog日志同步数据
 * @date 2021/3/6 23:14
 */
@RestController
@RequestMapping("/binlogClient")
public class CopyDataByBinlogClient {
    Log log = LogFactory.get(CopyDataByBinlogClient.class);
    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String REDIS_KEY_PREFIX = "user";

    @RequestMapping("/copy")
    public void copy() {
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("118.25.131.121",
                11111), "example", "", "");
        int batchSize = 1000;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            while (true) {
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                } else {
                    printEntry(message.getEntries());
                }
                connector.ack(batchId); // 提交确认
                // connector.rollback(batchId); // 处理失败, 回滚数据
            }
        } finally {
            connector.disconnect();
        }
    }

    private void printEntry(List<Entry> entrys) {
        for (Entry entry : entrys) {
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND
                    || !StrUtil.equals("gulimall_pms", entry.getHeader().getSchemaName()) || !StrUtil.equals("pms_spu_info", entry.getHeader().getTableName())) {
                continue;
            }
            RowChange rowChage = null;
            try {
                rowChage = RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                        e);
            }

            EventType eventType = rowChage.getEventType();
            log.info("binlog[{}:{}] , name[{}.{}] , eventType : {}",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType.name());
            for (RowData rowData : rowChage.getRowDatasList()) {
                List<Column> beforeColumnsList = rowData.getBeforeColumnsList();
                List<Column> afterColumnsList = rowData.getAfterColumnsList();
                if (eventType == EventType.DELETE) {
                    beforeColumnsList.stream().filter(Column::getIsKey).forEach(column -> this.redisTemplate.opsForHash().delete(REDIS_KEY_PREFIX, column.getValue()));
                    log.info("删除缓存");
                } else {
                    AtomicReference<String> primaryKey = new AtomicReference<>("");
                    JSONObject jsonObject = JSONUtil.createObj();
                    afterColumnsList.forEach(column -> {
                        jsonObject.putOpt(column.getName(), column.getValue());
                        if (column.getIsKey()) {
                            primaryKey.set(column.getValue());
                        }
                    });
                    this.redisTemplate.opsForHash().put(REDIS_KEY_PREFIX, primaryKey.get(), jsonObject.toString());
                    log.info("更新缓存");
                }
            }

        }
    }

}
